package util;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //基于HTTP请求
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求路劲
        String url = request.getRequestURI();

        //1.指定页面放行
        if (url.contains("/Login.jsp") || url.contains("/js/") || url.contains("/LoginServlet")) {
            filterChain.doFilter(request, response);
            System.out.println("Login.jsp通过");
        }else{

            //4.登陆状态放行
            String uname = (String) request.getSession().getAttribute("username");
            System.out.println(uname);
            //判断Session是否为空
            if (uname != null){
                filterChain.doFilter(request, response);
                System.out.println("loginForm通过");
            }else {
                request.setAttribute("error_msg","请登录");
                request.getRequestDispatcher("/Login.jsp").forward(request,response);
            }

        }


    }

    @Override
    public void destroy() {

    }
}
